<template>
  <t-dialog :header="header" :visible.sync="visible" :onClose="closeDialog" :closeOnOverlayClick="false"
    :confirmBtn="null" :cancelBtn="null" width="60%" top="6%">
    <div style="height: 60vh;">
      <div class="base-container" id="main">
        <t-loading text="加载中..." :fullscreen="false" attach="#main" :loading="applyLoading" size="medium">
        </t-loading>
        <!-- 基本信息 -->
        <t-form ref="form" :colon="true" class="step-form" :data="formData" :rules="rules" label-width="200px">

          <t-row style="align-items: stretch" :gutter="14">
            <t-col :span="12">
              <t-card class="step-card" size="small" title="">
                <t-row>
                  <t-col :span="12">
                    <t-form-item label="序号" name="sort">
                      <t-input-number :allowInputOverLimit="false" v-model='formData.sort' :min="1"></t-input-number>
                    </t-form-item>
                    <t-form-item label="指标名称" name="systemId">
                      <t-tree-select clearable @change="onProfTitIdChange" filterable style="width: 390px"
                        :treeProps="{ keys: { value: 'id' }, valueMode: 'onlyLeaf' }" v-model="formData.systemId"
                        :data="profTitOptions" placeholder="指标名称"></t-tree-select>
                    </t-form-item>
                    <t-form-item label="分值" name="score">
                      <!-- <t-input-number disabled :allowInputOverLimit="false" v-model='formData.score'
                    :min="1"></t-input-number> -->
                      {{ formData.score }}
                    </t-form-item>
                    <t-form-item label="备注" name="note">
                      {{ formData.note }}
                    </t-form-item>
                    <t-form-item label="排名" name="ranking" v-if="isShowRanking">
                      <div style="display: flex;flex-direction: column;">
                        <t-select style="width: 390px" placeholder="请选择" :options="dict.type.kjpt_score_ranking"
                          v-model="formData.ranking">
                        </t-select>
                        <div style="font-size: 12px;">科研项目、科技奖励及标准制定指标中，合作成果排名前三位纳入计分范围，按照1、0.8、0.6比例计分</div>
                      </div>
                    </t-form-item>
                    <t-form-item label="金额（万元）" name="money" v-if="isShowMoney">
                      <t-input-number :allowInputOverLimit="false" v-model='formData.money' :min="1"></t-input-number>
                    </t-form-item>

                    <!-- </t-col>
                  <t-col :span="6"> -->
                    <t-form-item label="成果名称" name="name">
                      <t-input style="width: 390px" placeholder="请输入" clearable v-model="formData.name"></t-input>
                    </t-form-item>

                    <t-form-item label="取得年度" name="year">
                      <!-- <t-input v-model="formData.year" clearable placeholder="请输入" style="width: 390px" /> -->
                      <t-date-picker mode="year" v-model="formData.year"></t-date-picker>
                    </t-form-item>
                    <t-form-item label="相关附件" name="projectFileData">
                      <file-upload v-model="projectFileData.fileIds" :moduleKey="projectFileData.moduleKey"
                        :fileList="projectFileData.fileLists" :multiple="true">
                        <t-button variant="outline">
                          <t-icon name="cloud-upload" slot="icon" />
                          点击上传
                        </t-button>
                      </file-upload>
                    </t-form-item>
                  </t-col>
                </t-row>
              </t-card>
            </t-col>
          </t-row>
          <t-row>
            <t-col :span="11" class="query-form-inline">
              <t-button theme="primary" type="submit" @click="onSubmit(1)">暂存</t-button>
            </t-col>
            <t-col :span="1" class="operation-container">
              <t-button theme="primary" type="submit" @click="onSubmit(2)">提交审批</t-button>
            </t-col>
          </t-row>
        </t-form>
      </div>
    </div>

  </t-dialog>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import FileUpload from "@/components/FileUpload/index.vue"
import { getDictList } from "@/api/system/dict/data";
import { getFiles } from "@/api/common";

export default {
  dicts: ["kjpt_score_ranking"],
  props: {
    objId: [String, Number],
    header: String,
    platformId: [String, Number],
  },
  components: {
    FileUpload,
  },
  data () {
    return {
      projectFileData: {
        id: 1,
        c1: "相关附件",
        c2: "否",
        moduleKey: "kjptzbfj",
        require: true,
        fileIds: [],
        fileLists: [],
        accept: "application/pdf,image/*"
      },
      visible: true,
      isShowRanking: false,
      isShowMoney: false,
      applyLoading: false,
      site_tag: import.meta.env.VITE_SITE_TAG,
      file_domain: VITE_FILE_DOMAIN,

      profTitOptions: [],

      formData: {
        id: null,
        sort: '',
        systemId: '',
        score: '',
        note: '',
        ranking: '',
        money: '',
        name: '',
        year: '',
        platformId: "",
      },
      rules: {
        sort: [
          {
            required: true,
            message: "序号不能为空",
          },
        ],
        systemId: [
          { required: true, message: "指标名称不能为空", type: "error" }
        ],
        name: [
          { required: true, message: "成果名称不能为空", type: "error" }
        ],
        year: [
          { required: true, message: "取得年度不能为空", type: "error" }
        ]
      },

    }
  },
  watch: {
    objId: {
      immediate: true,
      handler (val) {
        if (val) {
          this.formData.id = val;
          this.getList()
        }
      }
    },
    platformId: {
      immediate: true,
      handler (val) {
        if (val) {
          this.formData.platformId = val;
        }
      }
    },
  },
  async created () {
    this.getProfTitTreeSelect()
  },
  methods: {
    getList () {
      if (!this.formData.id) {
        return
      }
      this.$api.kjpt.project.scoreDetail(this.formData.id).then(response => {
        if (response.data) {
          Object.assign(this.formData, response.data)
          this.onProfTitIdChange()
        }
      }).catch((e) => {

      });

      getFiles(this.formData.id).then((res) => {
        const files = []
        res.data.forEach((item) => {
          files.push({
            name: item.fileName,
            url: item.fullFilePath,
            id: item.id,
            filePath: item.filePath
          })
        })
        this.projectFileData.fileLists = files || [];
        this.projectFileData.fileIds = files?.map(val => val.id) || [];
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getProfTitTreeSelect () {
      return this.$api.kjpt.project.systemTree().then(response => {
        this.profTitOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onProfTitIdChange () {

      this.$api.kjpt.project.systemDetail(this.formData.systemId).then(response => {
        if (response.data) {
          this.formData.score = response.data.score
          this.formData.note = response.data.note
        }
      }).catch((e) => {
        this.$message.error(e.toString());
      });

      var systemId = this.formData.systemId + ''
      if (systemId.length > 5) {
        systemId = systemId.substring(0, 5)
      }
      console.log(systemId);

      this.isShowRanking = false
      if (systemId.includes('10101') || systemId.includes('10102') || systemId.includes('10104')) {
        this.isShowRanking = true
      }

      this.isShowMoney = false
      if (systemId.includes('10201')) {
        this.isShowMoney = true
      }
    },

    closeDialog () {
      this.$emit("update:visible", false);
    },
    onSubmit (type) {
      const sysAttMainIds = [...this.projectFileData.fileIds]
      console.log(this.projectFileData, sysAttMainIds);

      if (type === 1) {
        if (this.formData.id) {
          this.$api.kjpt.project.updateScore({
            ...this.formData,
            sysAttMainVo: {
              sysAttMainIds
            }
          }).then(response => {
            this.$message.success('暂存成功');
            this.$emit("reload");
            this.closeDialog()
          }).catch((e) => {
            this.$message.error(e.toString());
          });
        } else {
          this.$api.kjpt.project.addScore({
            ...this.formData,
            sysAttMainVo: {
              sysAttMainIds
            }
          }).then(response => {
            this.$message.success('暂存成功');
            this.$emit("reload");
            this.closeDialog()
          }).catch((e) => {
            this.$message.error(e.toString());
          });
        }

      } else {
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            let loading = false;
            const confirmDia = this.$dialog.confirm({
              header: "审批提示",
              body: `是否确认提交？`,
              // confirmBtn:{
              //   content: loading?'提交中...':'提交',
              //   theme: 'primary',
              //   loading,
              // },
              theme: "warning",
              onConfirm: ({ e }) => {
                confirmDia.update({
                  confirmBtn: {
                    loading: true,
                  },
                })
                this.$api.kjpt.project.submitScore({
                  ...this.formData,
                  sysAttMainVo: {
                    sysAttMainIds
                  }
                }).then(response => {
                  this.$message.success('提交成功');
                  this.$emit("reload");
                  confirmDia.destroy();
                  loading = false
                  this.closeDialog()
                }).catch((e) => {
                  loading = false
                  confirmDia.update({
                    confirmBtn: {
                      loading: false,
                    },
                  })
                  this.$message.error(e.toString());
                });
              },
            })

          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        })
      }

    },
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>
